const pool = require('./db');

async function initDatabase() {
  try {
    const connection = await pool.getConnection();
    console.log('开始初始化数据库...');

    // 创建软件表
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS software (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        version VARCHAR(20) NOT NULL,
        description TEXT,
        category VARCHAR(50),
        file_path VARCHAR(255) NOT NULL,
        file_size INT NOT NULL,
        download_count INT DEFAULT 0,
        cover_image VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);

    // 创建用户表
    await connection.execute(`
      CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) NOT NULL UNIQUE,
        password VARCHAR(255) NOT NULL,
        role ENUM('user', 'admin') DEFAULT 'user',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);

    // 创建管理员用户
    await connection.execute(`
      INSERT IGNORE INTO users (username, password, role) VALUES (
        'admin',
        '$10$MkTk33N25LBkwc8YsH/S3.LSkdrKZNC92n7QBfBAesSkBQyBBxx9e',
        'admin'
      )
    `);
    console.log('创建管理员用户: 用户名admin, 密码123456');

    console.log('数据库初始化完成！');
    connection.release();
  } catch (error) {
    console.error('数据库初始化失败:', error.message);
  }
}

initDatabase();